package com.bieber.democamp.sharesession.session.redis;

import com.bieber.democamp.sharesession.session.AbstractSession;
import com.bieber.democamp.util.ObjectUtils;
import com.bieber.democamp.util.RedisClient;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.IOException;
import java.io.Serializable;
import java.util.HashMap;
import java.util.Map;

/**
 * Created by bieber on 2015/3/16.
 */
public class RedisSession extends AbstractSession {

    private static final Logger logger = LoggerFactory.getLogger(RedisSession.class);

    private byte[] sessionIdBytes;

    public RedisSession(String sessionId,int expireSecond) {
        super(sessionId);
        try {
            sessionIdBytes=ObjectUtils.object2Bytes(sessionId);
            if(!RedisClient.exist(sessionIdBytes)){
                Map<byte[],byte[]> cacheMap = new HashMap<byte[],byte[]>();
                cacheMap.put("init".getBytes(),"ok".getBytes());
                RedisClient.cacheMap(sessionIdBytes, cacheMap, expireSecond);
            }else{
                RedisClient.refreshExpire(sessionIdBytes, expireSecond);
            }
        } catch (IOException e) {
            logger.debug("failed to create session cache in redis",e);
            throw new IllegalStateException("failed to create session cache in redis",e);
        }
    }

    @Override
    public void setAttribute(String key, Serializable value) {
        try {
            RedisClient.putMapEntity(sessionIdBytes, ObjectUtils.object2Bytes(key), ObjectUtils.object2Bytes(value));
        } catch (IOException e) {
            logger.debug("failed to set session attribute [{}-{}] in redis",key,value, e);
            throw new IllegalStateException("failed to create session cache in redis",e);
        }
    }

    public Object getAttributes(String key){
        try {
            return RedisClient.getMapValue(sessionIdBytes, ObjectUtils.object2Bytes(key));
        } catch (IOException e) {
            logger.debug("failed to get session attribute key [{}] in redis", key, e);
            throw new IllegalStateException("failed to get session attribute in redis",e);
        }
    }

    @Override
    public Object removeAttribute(String key) {
        try {
            return RedisClient.removeMapValue(sessionIdBytes, ObjectUtils.object2Bytes(key));
        } catch (IOException e) {
            logger.debug("failed to remove session attribute key [{}] in redis", key, e);
            throw new IllegalStateException("failed to remove session attribute in redis",e);
        }
    }

}
